import SessionUtil, { JxbHttpClient } from '../../../data/session/session'
import SessionUserUtil from '../../../data/session/sessionUser';
import { RtLogUtil } from '../../../utils/log';
import { CommonBizLogicError } from '../../../utils/network';
import AppSceneUtil from '../../../data/common/appScene';
import InteractionUtil from '../../../shell/ui/interaction';
var Common = require('../../../utils/common.js');
var checkedlis = []
var result = []
Page({
  //页面的初始数据
  data: {
    sconIcon: "../../../asset/icon/scanStart.png",
    newPrice: 0,
    count: 0,
    msg: "商品数量最少为1",
    ismsg: false,
    modalHidden: false,
    testList: [],
    been_str: '',
    flag:true,
    defaultMsg:'还没有加入商品，快去扫描商品'
  },
  //商品数量-1
  sum(e) {
    let _this = this
    let a = e.currentTarget.dataset.code
    let code = a.split('-')[0]
    let num = Number(a.split('-')[1])
    let index = result.lastIndexOf(code)
    if (num > 1) {
      if(_this.data.flag){
        result.splice(index, 1)
        let newArr = result.join(',');
        console.log(newArr)
        _this.retainQrcode(newArr, _this)
      }
    }
      if(num == 1){
        var newList = this.data.testList
        newList.splice(e.currentTarget.dataset.num,1)
        result.splice(index, 1)
        let newArr = result.join(',');
        console.log(newArr)
        _this.retainQrcode(newArr, _this)
        console.log(result)
        if (newList.length == 0) {
          this.setData({
            sconIcon: "../../../asset/icon/scanStart.png",
            newPrice: 0,
            count: 0,
            msg: "商品数量最少为1",
            ismsg: false,
            modalHidden: false,
            testList: [],
            been_str: '',
            flag: true,
            defaultMsg: '还没有加入商品，快去扫描商品'
          })
        }
        this.setData({
          testList: newList,
        },()=>{
          this.priceChange()
        })
      }

  },
  //商品数量+1
  add(e) {
    let code = e.currentTarget.dataset.code;
    let _this = this
    result.push(code)
    console.log(result)
    let newResult = result.join(',')
    this.retainQrcode(newResult, _this)
  },
  //去支付
  goPayFunc(){
    if (this.data.newPrice == 0) {
      InteractionUtil.showAlert('请先扫描商品的二维码！', '提示')
      return false;
    }
    let been_str = this.data.been_str;
    (new JxbHttpClient).post({
      url: '/AppMaster/PosOrder/sweepCodeOrderBorn',
      data: {
        itemInfo: been_str
      }
    }).then(jxbResp=>{
      checkedlis = this.data.testList.map((item) => {
        return item.item_id
      })
      let sessionUser = SessionUserUtil.getInstanceSync()
      console.log('sessionUser',sessionUser)
      wx.navigateTo({
        url: '/pages/order/pay/pay?orderno=' + jxbResp.data.orderSn + "&paymoney=" + jxbResp.data.totalMoney + '&orders_id=' + jxbResp.data.orderId + '&backScanCode=1'
      })
    }).catch(err=>{
      this.setData({
        ismsg: true,
        msg: err.message
      })
      setTimeout(() => {
        this.setData({
          ismsg: false
        })
      }, 3000)
    })
  },
  goOrderConfirm(e) {
    var order = e.currentTarget.id.split('-');
    let _this = this
    Common.when_user_change_clear_the_storage(_this.goPayFunc)
  },
  //总价变化函数 数量变化
  priceChange() {
    if (this.data.testList.length != 0) {
      let allPrice = 0
      let allCount = 0
      for (let i = 0; i < this.data.testList.length; i++) {
        allCount += this.data.testList[i].car_number
        allPrice += this.data.testList[i].show_price * this.data.testList[i].car_number
      }
      this.setData({
        newPrice: allPrice,
        count: allCount
      })
    }
  },
  //调用二维码接口
  retainQrcode(res, _this) {
    this.setData({
      flag: false,
      // defaultMsg:'正在加载中'
    })
    let loadingTimeout = setTimeout(()=>{
      wx.showLoading({
        title: '正在加载...',
      })
    }, 300);
    (new JxbHttpClient).get({
      url: '/AppMaster/Item/ItemCodeSweep',
      data: {
        code: res,
      }
    }).then(jxbResp=>{
      clearTimeout(loadingTimeout)
      wx.hideLoading()
      console.log(jxbResp)
      if (jxbResp.data) {
        let productsList = jxbResp.data.productsList
        let been_str = jxbResp.data.item_been_str
        this.setData({
          testList: productsList,
          been_str: been_str,
        },()=>{
          this.setData({flag: true})
        })
      } else {
        if(result.length >0){
          result = result.slice(0, result.length - 1)
        }
        this.setData({
           flag: true,
           ismsg: true,
           msg: jxbResp.message,
           defaultMsg: '还没有加入商品，快去扫描商品'
         })
        setTimeout(() => {
          this.setData({
            ismsg: false
          })
        }, 3000)
      }
      _this.priceChange()
    }).catch(err=>{
      clearTimeout(loadingTimeout)
      wx.hideLoading()
      console.log(err)
      if(!(err instanceof CommonBizLogicError)){
        RtLogUtil.error(err.message, err.httpResponse)
      }
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  //扫描二维码
  scanCode() {
    let _this = this
    wx.scanCode({
      success(res) {
        let arr = res.result
        result.push(arr)
        console.log(result)
        let newResult = result.join(',')
        console.log(newResult)
        _this.retainQrcode(newResult, _this)
      },
      fail(err) {
        console.log(err)
        RtLogUtil.error('扫描二维码出错！', err.errMsg, err)
        if (err.errMsg != 'scanCode:fail cancel') {
          _this.setData({
            modalHidden: true
          })
        }
      }
    })
  },
  //关闭弹窗
  modalChange() {
    this.setData({
      modalHidden: false
    })
  },
 getUrlParam(url, name){
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    getApp().getSaleMode()
    SessionUtil.getInstance().then(()=>{
      AppSceneUtil.setPageScene(this)
      console.log('options',options)
      if(options && options.q) {
        const url = decodeURIComponent(options.q)
        result.push(url);
        let resultsArr = result.join(',');
        console.log(resultsArr)
        this.retainQrcode(resultsArr, this)
      }
    })
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    SessionUtil.getInstance().then(()=>{
      AppSceneUtil.setPageScene(this, false)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})